<template>
  <div class="person-goods-line-chart">
    <div ref="chartRef" :style="`width: 100%; height: ${height}`"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, onBeforeUnmount } from "vue";
import * as echarts from "echarts/core";
import { LineChart } from "echarts/charts";
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
} from "echarts/components";
import { CanvasRenderer } from "echarts/renderers";
import type { ECharts } from "echarts/core";

// 注册组件
echarts.use([
  LineChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  CanvasRenderer,
]);

const chartRef = ref<HTMLDivElement | null>(null);
let myChart: ECharts | null = null;

const { data, height,title } = defineProps<{
  data: {
    xAxis: string[];
    series: {
      name: string;
      data: number[];
    }[];
  };
  height: string;
  title: string;
}>();

watch(
  () => data,
  () => {
    if (myChart) {
      myChart.setOption(getOption());
    }
  },
  { deep: true }
);

onMounted(() => {
  if (chartRef.value) {
    myChart = echarts.init(chartRef.value);
    myChart.setOption(getOption());
  }
  window.addEventListener("resize", resizeChart);
});

onBeforeUnmount(() => {
  window.removeEventListener("resize", resizeChart);
  myChart?.dispose();
});

function resizeChart() {
  myChart?.resize();
}

function getOption() {
  return {
    title: {
      text: title,
      left: 10,
      top: 10,
      textStyle: {
        fontSize: 12,
        color: "#4E718F",
        fontWeight: "normal",
      },
    },
    tooltip: {
      trigger: "axis",
    },
    legend: {
      top: 10,
      textStyle: {
        fontSize: 12,
        color: "#415B73",
      },
    },
    grid: {
      top:50,
      left: 10,
      right: 20,
      bottom: 0,
      containLabel: true
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: data.xAxis,
      axisLabel: {
        color: "#4E718F",
      },
      axisLine: {
        lineStyle: {
          color: "#D8E2F1",
        },
      },
    },
    yAxis: {
      type: "value",
      axisLabel: {
        color: "#4E718F",
      },
      splitLine: {
        lineStyle: {
          color: "#D8E2F1",
        },
      },
    },
    series: data.series.map((item) => ({
      name: item.name,
      type: "line",
      data: item.data,
    })),
    color: ["#E9AF00", "#00AB84", "#00A0E9"], // 入境、出境、出岛颜色
  };
}
</script>

<style lang="less" scoped>
.person-goods-line-chart {
  flex: 1;
}
</style>
